package com.shenyue.nbtownlet.activity;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.databinding.ActivityOfficeBinding;
import com.shenyue.nbtownlet.model.DefaultModel;
import com.shenyue.nbtownlet.util.ActivityUtil;
import com.shenyue.nbtownlet.util.FileOpenUtil;
import com.shenyue.nbtownlet.util.MD5Util;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.File;

import okhttp3.Call;

public class OfficeActivity extends BaseActivity implements View.OnClickListener {
    private ActivityOfficeBinding binding;
    private String fileName;
    private String _url;
    private Handler mHandler = new Handler();

    /*两个在线预览office文档的地址：(浏览器都需要chrome的内核)
        1 google：https://docs.google.com/viewer?url=（输入你的文档在服务器中的地址）；
        2 微软：https://view.officeapps.live.com/op/view.aspx?src=(输入你的文档在服务器中的地址)；*/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_office);
        Bundle bundle = getIntent().getExtras();
        _url = bundle.getString(DefaultModel.URL);
        setActionBar(true, "文档预览");
        binding.btn.setOnClickListener(this);
        binding.progressLayout.showProgress();
        /*try {
            StringBuilder sb = new StringBuilder();
            sb.append("https://view.officeapps.live.com/op/view.aspx?src=");
            sb.append(URLEncoder.encode(url, "utf8"));
            binding.webView.loadUrl(sb.toString());
        } catch (Exception e) {
            binding.progressLayout.showContent();
        }*/

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                open(_url);
            }
        }, 320);
    }

    private void openFile(File file) {
        binding.progressLayout.showContent();
        FileOpenUtil.openFile(this, file);
    }

    private void openFile(String url) {
        binding.progressLayout.showContent();
        FileOpenUtil.openFileByUri(this, url);
    }

    private void open(final String url) {
        String $url = url;
        String fileType = $url.substring($url.lastIndexOf("."));

        String mDDirPath = ActivityUtil.getMSDCardPath();
        mDDirPath = mDDirPath + "/" + DefaultModel.DOWNLOAD_DIR_NAME;
        File file = new File(mDDirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        fileName = MD5Util.md5(url) + fileType;
        File pdf = new File(mDDirPath + "/" + fileName);
        if (pdf.exists()) {
            openFile(pdf);
            return;
        }
        RequestCall call = OkHttpUtils.get().url(url).build();
        call.execute(new FileCallBack(mDDirPath, fileName) {
            @Override
            public void inProgress(float progress, long total, int id) {
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                openFile(url);
            }

            @Override
            public void onResponse(File file, int id) {
                openFile(file);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn:
                open(_url);
                break;
        }
    }
}
